import { v3, Vec3 } from 'cc';
import { NodeUtil } from 'db://app-game/core/utils/NodeUtil';
import BTConditional from 'db://app-game/libs/math/behavior-tree/base/BTConditional';
import { NodeStatus } from 'db://app-game/libs/math/behavior-tree/enum';
import { Monster } from '../../ecs/biz/monster/Monster';
import { MonitorModelAttackComp } from '../../ecs/biz/monster/model/MonitorModelAttackComp';
import { smc } from '../../ecs/singleton/SingletonModuleComp';

/**
 * 判断锁定目标是否在攻击范围内
 *
 * 1. 获取锁定目标
 * 2. 判断锁定节点是否销毁
 * 3. 获取锁定目标位置
 * 4. 获取怪兽位置
 * 5. 判断距离
 */
export default class ConditionalMonsterAttack extends BTConditional {
  onUpdate(monster: Monster): NodeStatus {
    // 1.获取锁定目标
    if (!monster.get(MonitorModelAttackComp)) return NodeStatus.Failure;
    const lockTarget = monster.MonitorModelAttack.lockTarget;
    // 2.判断锁定节点是否销毁
    if (!lockTarget) {
      monster.remove(MonitorModelAttackComp);
      return NodeStatus.Failure;
    }

    // 3.获取锁定目标位置
    const lockTargetPos = NodeUtil.posConvert(v3(0, 0, 0), lockTarget, smc.level.LevelMap.mapNode);
    // 4.获取怪兽位置
    const monsterPos = NodeUtil.posConvert(
      v3(0, 0, 0),
      monster.MonsterView.node,
      smc.level.LevelMap.mapNode
    );

    // 5.判断距离
    const distance = Vec3.distance(monsterPos, lockTargetPos);
    if (distance > monster.MonsterModel.attackRange) return NodeStatus.Failure;

    return NodeStatus.Success;
  }
}
